#!/bin/sh
# Check elf files

if [ -z "$RPM_BUILD_ROOT" ]; then
	echo "No build root defined" >&2
	exit 1
fi

if [ ! -d "$RPM_BUILD_ROOT" ]; then
	echo "Invalid build root" >&2
	exit 1
fi

LIB="$(rpm --eval %{_lib})"
export LD_LIBRARY_PATH="$RPM_BUILD_ROOT/$LIB:$RPM_BUILD_ROOT/usr/$LIB"

find "$RPM_BUILD_ROOT" -type f \( -executable -o -name \*.so\* \) -a \
	\( ! -path $RPM_BUILD_ROOT/usr/lib/debug/\* -a \
	   ! -path $RPM_BUILD_ROOT/usr/src/debug/\* \) \
	-print0 |
xargs  --no-run-if-empty -0 file -N -L |
grep -e '\.so.*: ELF.*shared' -e ': ELF.*executable' |
while read match; do
	path="$(echo $match | cut -d':' -f1)"
	syspath="$(echo $path | sed -e "s#^$RPM_BUILD_ROOT##")"
	unused_libs="$(ldd -u -r $path 2> /dev/null | grep /)"
	if [ -n "$unused_libs" ]; then
		printf '%s\n' "Warning: unused libraries in $syspath: " >&2
		printf '%s\n' "$unused_libs" >&2
	fi
	if echo $match |grep -q shared; then
		undefined_symbols="$(ldd -r $path 2>&1 | grep '^undefined symbol: '| sed -e 's#^undefined symbol:##g' -e "s#($path).*##g" | tr -d '\n' | tr -d '\t')"
		if [ -n "$undefined_symbols" ]; then
			printf '%s\n' "Warning: undefined symbols in $syspath:$undefined_symbols" >&2
		fi
	fi
done
